package com.richie696.connect.startup;

import com.richie696.catalina.LifecycleException;
import com.richie696.catalina.config.ConfigParser;
import com.richie696.catalina.connector.Connector;
import com.richie696.connect.RequestProcessor;
import com.richie696.connect.Service;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

public class Bootstrap {

    private static final String DEFAULT_CONFIG = "/conf/server.xml";
    private static final Object daemonLock = new Object();
    private static volatile Bootstrap daemon = null;
    private ClassLoader catalinaLoader;
    private Service service;


    public Bootstrap init() throws LifecycleException {
        this.service = ConfigParser.getInstance().read(DEFAULT_CONFIG);
        this.catalinaLoader = ClassLoader.getSystemClassLoader();
        return this;
    }

    public void start() throws Exception {
        for (Connector connector : this.service.getConnectors()) {
            ServerSocket serverSocket = new ServerSocket(connector.getPort());
            this.service.addServerSocket(connector.getPort(), serverSocket);
            while (this.service.isStart()) {
                Socket socket = serverSocket.accept();
                RequestProcessor processor = new RequestProcessor(socket, connector);
                if (Objects.nonNull(connector.getExecutorBean())) {
                    connector.getExecutorBean().execute(processor);
                } else {
                    processor.start();
                }
            }
        }
    }

    public static void main(String[] args) {
        synchronized (daemonLock) {
            if (Bootstrap.daemon == null) {
                Bootstrap bootstrap = new Bootstrap();
                try {
                    bootstrap.init().start();
                    Bootstrap.daemon = bootstrap;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Thread.currentThread().setContextClassLoader(Bootstrap.daemon.catalinaLoader);
            }
        }
    }

}
